<?php
declare (strict_types=1);
namespace app\admin\controller;

use think\exception\ValidateException;
use think\facade\View;
use think\facade\Db;
use think\facade\Session;
use app\validate\admin\AdminUser as AdminUserValidate;
use app\admin\model\Admin as AdminModel;
class Login extends Base
{

    public function index()
    {
        if (!empty(session('admin'))){
            return redirect('/');
            //return redirect((string)url('index/index'));
        }
        return View::fetch();
    }
  
      /**
     * 后台登录
     */
    public function login(){

        //获取数据
        $data = request()->param();
        try {
            validate(AdminUserValidate::class)->check($data);
        }catch (ValidateException $exception) {
            return $this->success([], $exception->getMessage(), 0,400);
        }

//        if (!captcha_check($data['captcha'])){
//            return $this->success([], '验证码错误~', 0,400);
//        }
        $userInfo = new AdminModel();
        try {
            $isSuccess=$userInfo->findUser($data['username']);
        }catch (\ErrorException $exception){
            return $this->success([], '异常错误~', 0,400);
        }
        if ($isSuccess === null){
            return $this->success([],'用户不存在',0,400);
        }
        $password = sha1($data['password'].$isSuccess['salt']);
        if ($password != $isSuccess['password']){
            return $this->success([],'密码错误',0,400);
        }
        $timeAndIp=[
            'logintime' => time(),
            'loginip' => request()->ip()
        ];
        $userInfo->updateLoginTime($timeAndIp,$data['username']);
        Session('admin', $isSuccess['id']);
        if (Session::has('admin')){
            // 跳回之前的来源地址
            return $this->success([],'登录成功',0,200);
        }

    }

    /**
     * 退出登录
     * @return \think\response\Redirect
     */
    public function logout(){
        session('admin',null);
        return redirect((string)url('login/index'));
    }

}
